/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameheart.client.logic;

import gameheart.client.sprite.TextBoxSprite;
import gameheart.client.sprite.ImageResposity;
import gameheart.client.sprite.LabelSprite;
import gameheart.client.sprite.ImageSprite;
import gameheart.client.sprite.Sprite;
import gameheart.transport.Command;
import gameheart.transport.LocalTransporter;
import gameheart.transport.MyException;
import gameheart.transport.Transporter;
import gameheart.server.GameServerCanvas;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author win7
 */
public class CreateGameState extends State {

    CreateGameState(MainGame mainGame) {
        super(mainGame);
    }

    public void gameUpdate() {
        if (_menuSelectedIndex > -1) {
            try {
                MenuClick(_menuSelectedIndex);
            } catch (MyException ex) {
                Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnknownHostException ex) {
                Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void gameRender(Graphics g) {
        g.drawImage(background, 0, 0, 1024, 738 - 30, _mainGame);
        // avatar
//        for (int index = 0; index < sprite.size(); index++) {
//            sprite.get(index).draw(g);
//        }
        // menu
        for (int i = 0; i < _menus.size(); i++) {
            _menus.get(i).draw(g);
            //g.drawString(menuitem.get(i), _menus.get(i).getX() + 20, _menus.get(i).getY() + 20);
        }


        for (int index = 0; index < _labels.size(); ++index) {
            //g.drawString(_labelText.get(index), _labels.get(index).getX() + 10, _labels.get(index).getY() + _labels.get(index).getHeight() - 5);
            _labels.get(index).draw(g);
        }
        for (int index = 0; index < _textBoxs.size(); ++index) {
            _textBoxs.get(index).draw(g);
        }
    }
    Image background;
//    ArrayList<Sprite> sprite = new ArrayList<Sprite>();
    ArrayList<LabelSprite> _menus = new ArrayList<LabelSprite>();
    ArrayList<TextBoxSprite> _textBoxs = new ArrayList<TextBoxSprite>();
    ArrayList<LabelSprite> _labels = new ArrayList<LabelSprite>();
    int maxInput = 14;
    ImageResposity imageResposity;

    public void gameInit() {
        imageResposity = new ImageResposity();
        background = imageResposity.getImage("bg_main.jpg");

        //   sprite.add(new ImageSprite(805, 137, 60, 60, imageResposity, "avata_default.gif"));

        BufferedImage labelBG = imageResposity.getImage("menu.jpg");
        BufferedImage textboxBG = imageResposity.getImage("NewTextBox.jpg");
        _labels.add(new LabelSprite(100, 300, 125, 30, "Server port :", labelBG));
        _textBoxs.add(new TextBoxSprite(400, 300, 175, 30, "9876", maxInput, textboxBG));

        _labels.add(new LabelSprite(100, 400, 125, 30, "Player name :", labelBG));
        //  sprite.add(_labels.get(_labels.size() - 1));

        _textBoxs.add(new TextBoxSprite(400, 400, 175, 30, "ee", maxInput, textboxBG));

//        Sprite menuitems = new ItemSprite(750, 340, 100, 40, imageResposity, "menu.jpg");
        _menus.add(new LabelSprite(800, 425, 300, 30, "Create", labelBG));
        _menus.add(new LabelSprite(800, 545, 300, 30, "Back", labelBG));

    }

    private void ProcessMouseClick(MouseEvent e) {
        Rectangle mouseRect = new Rectangle(e.getX(), e.getY(), 5, 5);
        for (Sprite currentSpirite : _textBoxs) {
            Rectangle rect = new Rectangle(currentSpirite.getX(), currentSpirite.getY() + 30, currentSpirite.getWidth(), currentSpirite.getHeight());
            if (mouseRect.intersects(rect)) {
                currentGetInputIndex = _textBoxs.indexOf(currentSpirite);
                break;
            } else {
                currentGetInputIndex = -1;
            }
        }
        for (Sprite currentSpirite : _menus) {

            Rectangle rect = new Rectangle(currentSpirite.getX(), currentSpirite.getY() + 30, currentSpirite.getWidth(), currentSpirite.getHeight());
            if (mouseRect.intersects(rect)) {
                _menuSelectedIndex = _menus.indexOf(currentSpirite);
                break;
            }
        }

    }
    volatile int _menuSelectedIndex = -1;

    private void MenuClick(int menuIndex) throws MyException, UnknownHostException {
        switch (menuIndex) {
            case 0: {
                String userName = _textBoxs.get(1).getText().getMessage();
                if (userName.length() > 0) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(_textBoxs.get(0).getText().getMessage());
                    } catch (NumberFormatException ex) {
                        Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
                        return;
                    }
                    int maxCommand = 10;
                    ArrayBlockingQueue<Command> serverCommands = new ArrayBlockingQueue<Command>(maxCommand, true);
                    ArrayBlockingQueue<Command> clientCommands = new ArrayBlockingQueue<Command>(maxCommand, true);
                    Transporter serverTransporter = new LocalTransporter(serverCommands, clientCommands);
                    Transporter clientTransporter = new LocalTransporter(clientCommands, serverCommands);
                    GameServerCanvas gameServerCanvas = new GameServerCanvas();
                    try {
                        gameServerCanvas.InitServer(serverTransporter, port);
                    } catch (IOException ex) {
                        Logger.getLogger(CreateGameState.class.getName()).log(Level.SEVERE, null, ex);
                        return;
                    }
                    _mainGame._server = gameServerCanvas;
                    Thread th = new Thread(gameServerCanvas);
                    th.start();
                    ClientAdapter adapter = new ClientAdapter(clientTransporter);
                    _mainGame.setAdapter(adapter);
                    adapter.joinGame(userName);
                    _mainGame.ChangeGameState(GameStateIds.WaitUserStateId);
                }
                break;
            }
            case 1: {
                _mainGame.ChangeGameState(GameStateIds.MenuStateId);
                break;
            }
        }
        _menuSelectedIndex = -1;
    }

    private void ProcessKey(KeyEvent e) {
        if (e != null) {
            int keyCode = e.getKeyCode();
            if (currentGetInputIndex >= 0) {
                if (keyCode == KeyEvent.VK_ENTER) {
                    return;
                }
                if (keyCode == KeyEvent.VK_BACK_SPACE) {
                    _textBoxs.get(currentGetInputIndex).getText().removeChar();
                } else {
                    if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
                        _textBoxs.get(currentGetInputIndex).getText().addChar(e.getKeyChar());
                    }
                }
            }
        }
    }
    private volatile int currentGetInputIndex = -1;

    public void gameEnd() {
    }

    public void mouseClicked(MouseEvent e) {
        ProcessMouseClick(e);
    }

    public void keyPressed(KeyEvent e) {
        ProcessKey(e);
    }
}
